package com.six.interceptor;


import com.auth0.jwt.JWT;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.six.pojo.dto.AdminDto;
import com.six.result.MessageCode;
import com.six.result.ResultUtils;
import com.six.utils.JsonUtils;
import com.six.utils.ResponseUtils;
import com.six.utils.TokenUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;


public class LoginInterceptor implements HandlerInterceptor {

    private Logger log= LoggerFactory.getLogger(LoginInterceptor.class);

    //在处理器执行之前执行
    //如果返回true代表放行
    //如果返回false代表拦截
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        //1.获取客户端携带的token
        String token = request.getHeader("token");
        if(StringUtils.isEmpty(token)){
            token=request.getParameter("token");
        }

        //2.判断token是否为空
        if(StringUtils.isEmpty(token)){
            log.info("客户端没有携带token...");
            ResponseUtils.responseToJson(JsonUtils.objectToJson(ResultUtils.buildFail(MessageCode.TOKEN_NOT_EMPTY)),response);
            return false;
        }


        //3.验签
        if(!TokenUtils.verify(token)){
            log.info("验签失败:{}",token);
            ResponseUtils.responseToJson(JsonUtils.objectToJson(ResultUtils.buildFail(MessageCode.TOKEN_ERROR)),response);
            return false;
        }

        //4.获取载荷
        DecodedJWT decodedJWT = JWT.decode(token);
        Map<String, Claim> claims = decodedJWT.getClaims();

        AdminDto adminDto=new AdminDto();
        adminDto.setUsername(claims.get("username").asString());
        adminDto.setPhone(claims.get("phone").asString());
        adminDto.setImage(claims.get("image").asString());
        adminDto.setPerms(claims.get("perms").asString());
        adminDto.setName(claims.get("name").asString());
        adminDto.setId(claims.get("id").asLong());

        //5.绑定用户信息到当前线程
        AdminThreadLocal.setAdminDto(adminDto);

        //6.放行
        return true;
    }

    //在处理器执行完毕后,但是还没有进行视图的解析
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    //在处理器执行完毕后，并且视图已经解析完毕
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

        //移除当前线程绑定的用户信息
        AdminThreadLocal.removeAdminDto();

    }
}
